# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


"""WebHelpers used in tgext.zeroisp."""

from webhelpers import date, feedgenerator, html, number, misc, text
from webhelpers.feedgenerator import rfc2822_date
from webhelpers.util import SimplerXMLGenerator, iri_to_uri

class GeoRSS(feedgenerator.Rss201rev2Feed):
    def __init__(self, title, link, description, language=None, author_email=None,
            author_name=None, author_link=None, subtitle=None, categories=None,
            feed_url=None, feed_copyright=None, feed_guid=None, ttl=None,
            ):

        feedgenerator.Rss201rev2Feed.__init__(self,title, link, description, language, author_email,
            author_name, author_link, subtitle, categories,
            feed_url, feed_copyright, feed_guid, ttl,
            )

    def write(self, outfile, encoding):
        handler = SimplerXMLGenerator(outfile, encoding)
        handler.startDocument()
        handler.startElement(u"rss", {u"version": self._version,
                                      u'xmlns:georss':"http://www.georss.org/georss"})
        handler.startElement(u"channel", {})
        handler.addQuickElement(u"title", self.feed['title'])
        handler.addQuickElement(u"link", self.feed['link'])
        handler.addQuickElement(u"description", self.feed['description'])
        if self.feed['language'] is not None:
            handler.addQuickElement(u"language", self.feed['language'])
        for cat in self.feed['categories']:
            handler.addQuickElement(u"category", cat)
        if self.feed['feed_copyright'] is not None:
            handler.addQuickElement(u"copyright", self.feed['feed_copyright'])
        handler.addQuickElement(u"lastBuildDate", rfc2822_date(self.latest_post_date()).decode('ascii'))
        if self.feed['ttl'] is not None:
            handler.addQuickElement(u"ttl", self.feed['ttl'])
        self.write_items(handler)
        self.endChannelElement(handler)
        handler.endElement(u"rss")


    def add_item(self, title, link, description, author_email=None,
            author_name=None, author_link=None, pubdate=None, comments=None,
            unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None,
            google_lng=None, google_lat=None):
            """
            Adds an item to the feed. All args are expected to be Python Unicode
            objects except pubdate, which is a datetime.datetime object, and
            enclosure, which is an instance of the Enclosure class.

            """
            georss=None
            if google_lng and google_lat:
                georss="%s %s" %(google_lat,google_lng)
            self.items.append({
                'title': title,
                'link': iri_to_uri(link),
                'description': description,
                'author_email': author_email,
                'author_name': author_name,
                'author_link': author_link,
                'pubdate': pubdate,
                'comments': comments,
                'unique_id': unique_id,
                'enclosure': enclosure,
                'categories': categories or (),
                'item_copyright': item_copyright,
                'ttl': ttl,
                'georss:point': georss
            })

    def write_items(self, handler):
        for item in self.items:
            handler.startElement(u"item", {})
            handler.addQuickElement(u"title", item['title'])
            handler.addQuickElement(u"link", item['link'])
            if item['description'] is not None:
                handler.addQuickElement(u"description", item['description'])

            # Author information.
            if item["author_name"] and item["author_email"]:
                handler.addQuickElement(u"author", "%s (%s)" % \
                    (item['author_email'], item['author_name']))
            elif item["author_email"]:
                handler.addQuickElement(u"author", item["author_email"])
            elif item["author_name"]:
                handler.addQuickElement(u"dc:creator", item["author_name"], {"xmlns:dc": u"http://purl.org/dc/elements/1.1/"})

            if item['pubdate'] is not None:
                handler.addQuickElement(u"pubDate", rfc2822_date(item['pubdate']).decode('ascii'))
            if item['comments'] is not None:
                handler.addQuickElement(u"comments", item['comments'])
            if item['unique_id'] is not None:
                handler.addQuickElement(u"guid", item['unique_id'])
            if item['ttl'] is not None:
                handler.addQuickElement(u"ttl", item['ttl'])
            if item['georss:point'] is not None:
                handler.addQuickElement(u"georss:point", item['georss:point'])
            # XXX DISABLED: these are defined at the feed level.
            #if item['generator'] is not None:
            #    handler.addQuickElement(u"generator", item['generator'])
            #if item['source'] is not None:
            #    handler.addQuickElement(u"source", item['source'])

            # Enclosure.
            if item['enclosure'] is not None:
                handler.addQuickElement(u"enclosure", '',
                    {u"url": item['enclosure'].url, u"length": item['enclosure'].length,
                        u"type": item['enclosure'].mime_type})

            # Categories.
            for cat in item['categories']:
                handler.addQuickElement(u"category", cat)

            handler.endElement(u"item")



feed = GeoRSS(
                title=u"Poynter E-Media Tidbits",
                link=u"http://www.poynter.org/column.asp?id=31",
                description=u"A group weblog by the sharpest minds in online media/journalism/publishing.",
                language=u"en",
                author_email=u"author_email",
                author_name=u"author_name",
                author_link=u"author_link",
                subtitle=u"subtitle",
                categories=[u"categories"],
                feed_url=u"feed_url",
                #generator=u"generator"
                )
feed.add_item(title="Hello", link=u"http://www.holovaty.com/test/", description="Testing.",
              google_lng="11.119902", google_lat="45.258697")
fp = open('test.rss', 'w')
feed.write(fp, 'utf-8')
fp.close()


